<script setup>
import PageHeader from "@/views/Common/PageHeader.vue";
import {useAddressStore} from "@/stores/address.js";
import {RegionFullText} from "v-region";
import {ref, watch,onMounted} from 'vue'
import {ElMessage} from "element-plus";
const addressList=useAddressStore().addressList
import { useRoute } from 'vue-router'
import {useUserStore} from "@/stores/user.js";
import {createOrderAPI} from "@/apis/order.js";
import router from "@/router/index.js";

const radio=ref()


const goodsData=ref([])

const totalPrice=ref(0)

onMounted(()=>{
  calculateTotal(goodsData.value)
  //获取上一个路由传过来的商品列表参数
  goodsData.value=JSON.parse(useRoute().params.goods)
})

//监听data，刷新总价
watch(goodsData,(newValue,oldValue)=>{
  calculateTotal(newValue)
},{deep:true})

function calculateTotal(newValue) {
  totalPrice.value=0
  newValue.forEach((item,index)=>{
    item.goods.forEach((item,index)=>{
      totalPrice.value+=item.price*item.amount
    })
  })
}

function handleSub(index1,index2) {
  if(goodsData.value[index1].goods[index2].amount<=1){
    ElMessage({
      type:'warning',
      message:'最少购买1件'
    })
    return
  }
  goodsData.value[index1].goods[index2].amount--
}
function handleAdd(index1,index2) {

  if(goodsData.value[index1].goods[index2].amount>=999){
    ElMessage({
      type:'warning',
      message:'最多购买999件'
    })
    return
  }
  goodsData.value[index1].goods[index2].amount++
}

const orderList=ref([
  {
    shopId:'',
    buyerId:'',
    aid:'',
    notes:'',
    orderTotal:'',
    createTime:'',
    updateTime:'',
    goodsList:[
      {
        gid:'',
        price:'',
        amount:'',
        subTotal:''
      },
      {
        gid:'',
        price:'',
        amount:'',
        subTotal:''
      }
    ],

  },
  {

  }
])

let orders=[]

const submitOrder=async (orderList)=>{
  orderList.forEach((item)=>{
    createOrderAPI(item).then((res)=>{
      console.log(res)
      if(res.code===200){
        //获取订单号
        orders.push(res.data)
        //跳转到支付页面
        toPay()
      }else{
        ElMessage({
          type:'error',
          message:'订单提交失败'
        })
      }
    })
  })
}

function createOrder() {
  if(radio.value===undefined){
    ElMessage({
      type:'warning',
      message:'请选择收货地址！'
    })
  }else{
    const orderList=[]
    goodsData.value.forEach((item,index)=>{
      // const order={
      //   shopId:item.shopId,
      //   buyerId:useUserStore().userInfo.uid,
      //   aid:radio.value.aid,
      //   notes:item.notes,
      //   orderTotal:0,
      //   createTime:nowDate(new Date()),
      //   updateTime:nowDate(new Date()),
      //   goodsList:[],
      // }
      const order={
        shop_id:item.shopId,
        buyer_id:useUserStore().userInfo.uid,
        address_id:radio.value.aid,
        order_message:item.notes,
        //orderTotal:0,
        //createTime:nowDate(new Date()),
        //updateTime:nowDate(new Date()),
        items:[],
      }
      item.goods.forEach((goods,index)=>{
        //order.orderTotal+=goods.price*goods.amount
        const g={
          gid:goods.gid,
          unit_price:goods.price,
          amount:goods.amount,
          //subTotal:goods.price*goods.amount
        }
        order.items.push(g)
      })
      orderList.push(order)
    })
    //提交订单到服务器
    submitOrder(orderList)

  }
}
const loading=ref(false)
let timer=null

function toPay() {
  //显示加载层
  loading.value=true
  //倒计时2s
  let TIME_COUNT= 2;
  timer=setInterval(() => {
    if (TIME_COUNT.value >=1 ) {
      //限制倒计时区间
      TIME_COUNT.value--;

    } else {
      //清除定时器
      clearInterval(timer)
      //关闭加载层
      loading.value=false
      router.replace({
        path: "/pay",
        query: {
          date:new Date().getTime(),
          total:totalPrice.value,
          data:JSON.stringify(orders),
          type:'direct'
        }
      })
    }
  }, 800);
}

</script>

<template>
  <div class="header"><page-header></page-header></div>
  <div class="logo">
    <img style="height: 60px;width: auto;margin-left: 40px;margin-top: 20px" src="../../assets/SAS-logo.png" alt="">
  </div>

  <div class="detailBox" v-loading="loading">
    <div class="addressBox">
      <div class="header" >
        <h3 >确认收货地址</h3>
      </div>
      <div style="margin-top: 70px">
        <el-radio-group v-model="radio" @change="console.log(radio)">
          <el-radio style="height: 100px;margin-bottom: 10px" v-for="(item,index) in addressList" :value="item" :border="false">
            <template #default>
              <div class="addressCard" >
                <div class="left">
                  <el-icon size="30"><Location /></el-icon>
                </div>
                <div class="right">
          <span >
             <el-tag type="danger" style="width: 35px;height: 18px;font-weight: bold" v-if="item.isDefault">默认</el-tag>
          <RegionFullText separator=" " v-model="addressList[index]"/>
        </span>
                  <span style="font-weight: bold;font-size: 14px" >{{item.address}}</span>
                  <div>
                    <span>{{ item.receiver_name }}&nbsp;&nbsp; </span><span>{{item.phoneNumber}}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-radio>
        </el-radio-group>
      </div>
    </div>

    <div class="orderBox">
      <h3>确认订单信息</h3>
      <div class="label">
        <span style="margin-left: 15px; margin-right: 250px">店铺宝贝</span>
        <span style="margin-right: 100px">商品规格</span>
        <span style="margin-right: 60px">原价</span>
        <span style="margin-right: 200px">数量</span>
        <span style="margin-right: 15px">小计</span>
      </div>


      <div class="goodsCard" v-for="(data ,index1) in goodsData">
        <div class="goodsShop">
          <span >{{data.shopName}}</span>
        </div>
        <div class="goods" v-for="(goods,index2) in data.goods">
          <img style="width: 80px;height: 80px;border-radius: 10px" :src="goods.img">
          <div style="width: 230px;padding: 0 15px"><span>{{goods.title}}</span></div>
          <div style="width: 130px"><span>默认</span></div>
          <div style="width: 60px"><span>￥{{goods.price}}</span></div>
            <el-input  style="height: 30px;width: 125px"

                       v-model="goods.amount"
            @change="goods.amount=goods.amount>999?999:goods.amount">
              <template #prepend>
                <el-button @click="handleSub(index1,index2)">-</el-button>
              </template>
              <template #append>
                <el-button @click="handleAdd(index1,index2)">+</el-button>
              </template>
            </el-input>
          <div style="margin-left: 100px"><span style="color: #ff5000">￥{{(goods.price*goods.amount).toFixed(2)}}</span></div>
        </div>
        <div class="note">
          <span>订单备注&nbsp;</span>
          <el-input style="width: 300px;margin-top: 0" placeholder="请输入备注，付款后商家可见" v-model="data.notes"></el-input>
        </div>

      </div>

      <div class="submitOrder" style="height: 60px;width: 100%;margin-top: 50px">
        <span style="font-size: 12px">合计</span>
        <span style="font-size: 14px;color: #ff5000">￥</span>
        <span style="font-size: 22px;color: #ff5000">{{ totalPrice.toFixed(2) }}</span>
        <el-button style="width: 180px;
        height:40px;
        float: right;
        background-color: #ff5000;
        color: white;
        border-radius: 8px"
        @click="createOrder">
          提交订单</el-button>
      </div>

    </div>

  </div>



</template>

<style scoped lang="less">
.detailBox{
  width: 100%;
  height: auto;
  background-color: #f3f6f8;

  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content:  flex-start;
  align-items: center;
  align-content: stretch;
  gap: 20px
}

.header{
  width: 100%;
  height: 30px;
}
.logo{
  width: 100%;
  height: 100px;
  background-color: #f3f6f8;
}
.addressBox{
  width: 900px;
  height: auto;

  background-color: white;
  border-radius: 10px;
  padding:10px 20px;

  display: flex;
  flex-direction: column;
  flex-wrap: wrap;

}

.addressCard{
  width: 235px;
  height: 100px;
  border: rgba(132, 132, 132, 0.74) 1px solid;
  border-radius: 10px;
  margin-right: 10px;
  padding:10px;

  display: flex;
  flex-direction: row;
}
.addressCard:hover{
  border-color: #409EFF;
}
.left{
  width: 50px;
  margin-top: 10px;
}
.right{
  height: 100px;
  width: 195px;

  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

.right span{

  font-size: 12px;
  line-height: 25px;

  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
}

.orderBox{
  width: 900px;
  height: auto;
  background-color: white;
  border-radius: 10px;
  padding:10px 20px;
}

::v-deep .el-radio__input {
  display: none ;
}

.label{
  width: 100%;
  height: 50px;
  background-color: #f3f6f8;
  font-size: 14px;
  color: #11192d;
  border-radius: 10px;
  line-height: 50px;
}

.goodsCard{
  width: auto;
  height: auto;
  margin-top: 20px;
}
.goodsShop{
  width: 100%;
  height: 40px;
  background-color:#f3f6f8 ;
  border-radius: 10px 10px 0 0;
  line-height: 40px;
  padding: 0 15px ;
  font-weight: bold;
}

.goods{
  width: 100%;
  height: 110px;
 // background-color: #409EFF;

  padding: 10px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
.note{
  width: 100%;
  height: 45px;
  padding: 10px;
  margin-top: 10px;
  border-radius: 0 0 10px 10px;
  background-color:#f3f6f8 ;
}
</style>